import React, { useState, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { 
  Card, Input, Button, Select, Row, Col, Typography, Empty, 
  Spin, Slider, message, Space, Tag 
} from 'antd';
import { 
  SearchOutlined, FilterOutlined, StarOutlined, 
  EnvironmentOutlined, DollarOutlined, CalendarOutlined 
} from '@ant-design/icons';
import { ProductCard } from '@/components';
import { searchService } from '@/services';
import { SearchParams, SearchSortBy, Campus, Faculty, DEFAULT_SEARCH_PARAMS, SEARCH_SORT_BY_DISPLAY_NAMES } from '@/types/search';
import { Product } from '@/types/product';

const { Text } = Typography;
const { Option } = Select;

const SearchPage: React.FC = () => {
  const [searchParams] = useSearchParams();
  const [searchText, setSearchText] = useState(searchParams.get('q') || '');
  const [category, setCategory] = useState<string>(searchParams.get('category') || 'all');
  const [sortBy, setSortBy] = useState<SearchSortBy>(DEFAULT_SEARCH_PARAMS?.sortBy || SearchSortBy.RELEVANCE);
  const [priceRange, setPriceRange] = useState<[number, number]>([0, 5000]);
  const [campus, setCampus] = useState<Campus | undefined>(undefined);
  const [faculty, setFaculty] = useState<Faculty | undefined>(undefined);
  
  const [searchResults, setSearchResults] = useState<Product[]>([]);
  const [totalResults, setTotalResults] = useState(0);
  const [loading, setLoading] = useState(false);
  const [showFilters, setShowFilters] = useState(false);

  // 分类选项
  const categoryOptions = [
    { label: '全部', value: 'all' },
    { label: '电子产品', value: 'electronics' },
    { label: '教材资料', value: 'books' },
    { label: '生活用品', value: 'daily' },
    { label: '服装服饰', value: 'clothing' },
    { label: '运动器材', value: 'sports' },
  ];

  // 排序选项
  const sortOptions = Object.entries(SEARCH_SORT_BY_DISPLAY_NAMES)
    .filter(([key]) => key !== SearchSortBy.DISTANCE) // 暂时不显示距离排序
    .map(([value, label]) => ({ label, value }));

  // 校区选项
  const campusOptions = [
    { label: '全部校区', value: undefined },
    { label: '主校区', value: Campus.MAIN },
    { label: '东校区', value: Campus.EAST },
    { label: '西校区', value: Campus.WEST },
  ];

  // 学院选项
  const facultyOptions = [
    { label: '全部学院', value: undefined },
    { label: '计算机学院', value: Faculty.COMPUTER_SCIENCE },
    { label: '电子信息学院', value: Faculty.ELECTRONICS },
    { label: '机械工程学院', value: Faculty.MECHANICAL },
    { label: '经济管理学院', value: Faculty.ECONOMICS_MANAGEMENT },
  ];

  // 搜索函数
  const handleSearch = async () => {
    if (!searchText.trim()) {
      message.warning('请输入搜索关键词');
      return;
    }

    try {
      setLoading(true);
      
      const searchParams: SearchParams = {
        keyword: searchText,
        category: category === 'all' ? undefined : category as any,
        sortBy,
        priceRange: {
          min: priceRange[0],
          max: priceRange[1]
        },
        campus,
        faculty,
        page: 1,
        pageSize: 20
      };

      const result = await searchService.searchProducts(searchParams);
      setSearchResults(result.products || []);
      setTotalResults(result.total || 0);

      // 更新URL参数
      const newSearchParams = new URLSearchParams();
      if (searchText) newSearchParams.set('q', searchText);
      if (category !== 'all') newSearchParams.set('category', category);
      if (campus) newSearchParams.set('campus', campus);
      if (faculty) newSearchParams.set('faculty', faculty);
      
      window.history.replaceState({}, '', `${window.location.pathname}?${newSearchParams}`);

    } catch (error) {
      message.error('搜索失败，请稍后重试');
      console.error('搜索错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 处理热门搜索词点击
  const handleHotKeywordClick = (keyword: string) => {
    setSearchText(keyword);
    setTimeout(() => handleSearch(), 100);
  };

  // 清空筛选条件
  const handleClearFilters = () => {
    setCategory('all');
    setPriceRange([0, 5000]);
    setCampus(undefined);
    setFaculty(undefined);
  };

  // 页面加载时执行搜索
  useEffect(() => {
    if (searchText) {
      handleSearch();
    }
  }, [searchText, searchParams.get('q')]);

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      {/* 页面标题 */}
      <div className="text-center mb-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-2">商品搜索</h1>
        <p className="text-gray-600">快速找到您心仪的校园二手商品</p>
      </div>
      
      {/* 搜索栏 */}
      <Card className="shadow-sm border-0 mb-6">
        <div className="max-w-6xl mx-auto">
          <Row gutter={[12, 12]} align="middle">
            <Col xs={24} md={10}>
              <Input
                placeholder="输入商品名称、关键词..."
                prefix={<SearchOutlined className="text-gray-400" />}
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                onPressEnter={handleSearch}
                size="large"
                className="h-12 rounded-lg"
              />
            </Col>
            <Col xs={12} md={3}>
              <Select 
                value={category} 
                onChange={(value: string) => setCategory(value)}
                size="large"
                className="w-full h-12 rounded-lg"
              >
                {categoryOptions.map(option => (
                  <Option key={option.value} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
            </Col>
            <Col xs={12} md={3}>
              <Select 
                value={sortBy} 
                onChange={(value: SearchSortBy) => setSortBy(value)}
                size="large"
                className="w-full h-12 rounded-lg"
              >
                {sortOptions.map(option => (
                  <Option key={option.value} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
            </Col>
            <Col xs={12} md={3}>
              <Button 
                type="default" 
                onClick={() => setShowFilters(!showFilters)}
                size="large"
                className="w-full h-12 rounded-lg"
                icon={<FilterOutlined />}
              >
                筛选
              </Button>
            </Col>
            <Col xs={12} md={5}>
              <Button 
                type="primary" 
                onClick={handleSearch}
                size="large"
                className="w-full h-12 bg-blue-600 hover:bg-blue-700 rounded-lg"
                icon={<SearchOutlined />}
                loading={loading}
              >
                搜索
              </Button>
            </Col>
          </Row>
          
          {/* 高级筛选 */}
          {showFilters && (
            <div className="mt-4 p-4 bg-gray-50 rounded-lg border">
              <Row gutter={[16, 16]}>
                <Col xs={24} md={6}>
                  <div>
                    <div className="text-sm font-medium text-gray-700 mb-2">
                      <DollarOutlined className="mr-1" />价格区间
                    </div>
                    <div className="px-2">
                      <Slider
                        range
                        min={0}
                        max={5000}
                        value={priceRange}
                        onChange={(value: [number, number]) => setPriceRange(value)}
                        tooltip={{ formatter: (value) => `¥${value}` }}
                      />
                      <div className="flex justify-between text-xs text-gray-500 mt-1">
                        <span>¥{priceRange[0]}</span>
                        <span>¥{priceRange[1]}</span>
                      </div>
                    </div>
                  </div>
                </Col>
                <Col xs={12} md={4}>
                  <div>
                    <div className="text-sm font-medium text-gray-700 mb-2">
                      <EnvironmentOutlined className="mr-1" />校区
                    </div>
                    <Select
                      value={campus}
                      onChange={(value: Campus | undefined) => setCampus(value)}
                      className="w-full"
                      placeholder="选择校区"
                      allowClear
                    >
                      {campusOptions.map(option => (
                        <Option key={option.value || 'all'} value={option.value}>
                          {option.label}
                        </Option>
                      ))}
                    </Select>
                  </div>
                </Col>
                <Col xs={12} md={4}>
                  <div>
                    <div className="text-sm font-medium text-gray-700 mb-2">
                      <StarOutlined className="mr-1" />学院
                    </div>
                    <Select
                      value={faculty}
                      onChange={(value: Faculty | undefined) => setFaculty(value)}
                      className="w-full"
                      placeholder="选择学院"
                      allowClear
                    >
                      {facultyOptions.map(option => (
                        <Option key={option.value || 'all'} value={option.value}>
                          {option.label}
                        </Option>
                      ))}
                    </Select>
                  </div>
                </Col>
                <Col xs={24} md={6}>
                  <div className="flex items-end h-full space-x-2">
                    <Button onClick={handleClearFilters} className="flex-1">
                      清空筛选
                    </Button>
                  </div>
                </Col>
              </Row>
            </div>
          )}
        </div>
      </Card>

      {/* 搜索结果统计 */}
      {loading ? (
        <div className="text-center py-8">
          <Spin size="large" />
          <div className="mt-2 text-gray-600">搜索中...</div>
        </div>
      ) : searchResults.length > 0 ? (
        <>
          <div className="mb-6">
            <div className="flex justify-between items-center">
              <div>
                <span className="text-gray-600">找到 </span>
                <span className="font-bold text-blue-600">{totalResults}</span>
                <span className="text-gray-600"> 件相关商品</span>
                
                {/* 筛选条件标签 */}
                <div className="mt-2 flex flex-wrap gap-2">
                  {searchText && (
                    <Tag closable onClose={() => setSearchText('')}>
                      关键词: {searchText}
                    </Tag>
                  )}
                  {category !== 'all' && (
                    <Tag closable onClose={() => setCategory('all')}>
                      分类: {categoryOptions.find(opt => opt.value === category)?.label}
                    </Tag>
                  )}
                  {campus && (
                    <Tag closable onClose={() => setCampus(undefined)}>
                      校区: {campusOptions.find(opt => opt.value === campus)?.label}
                    </Tag>
                  )}
                  {faculty && (
                    <Tag closable onClose={() => setFaculty(undefined)}>
                      学院: {facultyOptions.find(opt => opt.value === faculty)?.label}
                    </Tag>
                  )}
                  {(priceRange[0] > 0 || priceRange[1] < 5000) && (
                    <Tag closable onClose={() => setPriceRange([0, 5000])}>
                      价格: ¥{priceRange[0]} - ¥{priceRange[1]}
                    </Tag>
                  )}
                </div>
              </div>
              
              <div className="text-sm text-gray-500">
                排序方式: {sortOptions.find(opt => opt.value === sortBy)?.label}
              </div>
            </div>
          </div>

          {/* 搜索结果网格 */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            {searchResults.map((product) => (
              <ProductCard
                key={product.id}
                product={product}
                showFavorite={true}
                showActions={true}
                size="medium"
                onClick={() => window.open(`/products/detail/${product.id}`, '_blank')}
              />
            ))}
          </div>
        </>
      ) : searchText ? (
        <Card className="shadow-sm border-0">
          <Empty 
            description={
              <div className="text-center">
                <div className="text-gray-600 mb-2">暂无搜索结果</div>
                <div className="text-sm text-gray-500 mb-4">
                  没有找到与"{searchText}"相关的商品
                </div>
                <Space>
                  <Button type="primary" onClick={handleClearFilters}>
                    清空筛选条件
                  </Button>
                  <Button onClick={() => setSearchText('')}>
                    重新搜索
                  </Button>
                </Space>
              </div>
            }
          />
        </Card>
      ) : (
        <>
          {/* 热门搜索推荐 */}
          <Card className="shadow-sm border-0 mb-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">
              <StarOutlined className="mr-2" />热门搜索
            </h3>
            <div className="flex flex-wrap gap-3">
              {['iPhone', '笔记本电脑', '教材', '考研资料', '耳机', '运动鞋', '自行车', '平板电脑'].map(keyword => (
                <Button 
                  key={keyword}
                  type="default" 
                  size="middle"
                  className="text-gray-700 hover:text-blue-600 border border-gray-200 hover:border-blue-300 rounded-lg"
                  onClick={() => handleHotKeywordClick(keyword)}
                >
                  {keyword}
                </Button>
              ))}
            </div>
          </Card>

          {/* 分类推荐 */}
          <Card className="shadow-sm border-0">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">
              <CalendarOutlined className="mr-2" />热门分类
            </h3>
            <Row gutter={[16, 16]}>
              {categoryOptions.slice(1).map(category => (
                <Col xs={12} sm={8} md={6} lg={4} key={category.value}>
                  <div 
                    className="p-4 text-center border border-gray-100 rounded-lg hover:border-blue-300 hover:bg-blue-50 cursor-pointer transition-all"
                    onClick={() => {
                      setCategory(category.value);
                      setSearchText(category.label);
                      setTimeout(() => handleSearch(), 100);
                    }}
                  >
                    <div className="text-2xl mb-2">{getCategoryIcon(category.value)}</div>
                    <div className="font-medium text-gray-900">{category.label}</div>
                    <div className="text-xs text-gray-500 mt-1">热门商品</div>
                  </div>
                </Col>
              ))}
            </Row>
          </Card>
        </>
      )}

      {/* 搜索建议（仅在搜索结果存在时显示） */}
      {searchResults.length > 0 && (
        <div className="mt-8 p-6 bg-white rounded-lg border">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">相关搜索</h3>
          <div className="flex flex-wrap gap-2">
            {['笔记本电脑', '平板电脑', '二手手机', '耳机音响'].map(tag => (
              <Button 
                key={tag}
                type="text" 
                size="small"
                className="text-gray-600 hover:text-blue-600 border border-gray-200 hover:border-blue-300 rounded-lg"
                onClick={() => handleHotKeywordClick(tag)}
              >
                {tag}
              </Button>
            ))}
          </div>
        </div>
      )}
    </div>
  );

  // 获取分类图标
  function getCategoryIcon(category: string): string {
    const icons: Record<string, string> = {
      electronics: '📱',
      books: '📚',
      clothing: '👕',
      daily: '🏠',
      sports: '⚽'
    };
    return icons[category] || '📦';
  }
};

export default SearchPage;